package com.webserver.controller;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.Article;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ArticleController {
    //保存文章的目录名字
    private static String articleDirName = "./articles/";

    static {
        //程序加载时判断目录是否存在，不存在则自动创建
        File articleDir = new File(articleDirName);
        if (!articleDir.exists()) {
            articleDir.mkdirs();
        }
    }

    public void writeArticle(HttpRequest request, HttpResponse response) {
        System.out.println("正在保存文章...");
        String title = request.getParameters("title");
        String content=request.getParameters("content");
        String author = request.getParameters("author");
        System.out.println(title + "," + content);

        //判断值是否为空
        if (title == null || content == null || author == null) {
            response.setEntity(new File("./webapps/myweb/article_fail.html"));
            return;
        }

        Article article = new Article(title, content, author);
        try (
                ObjectOutputStream oos = new ObjectOutputStream(
                        new FileOutputStream(articleDirName + title + ".obj")
                );
        ) {
            oos.writeObject(article);
            //保存成功
            response.setEntity(new File("./webapps/myweb/article_success.html"));
            System.out.println("文章保存成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}














